package org.hxzon.util;

import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;

public class StringUtil {
    public static String escapeSql(String input) {
        input = StringUtils.replace(input, "'", "''");
//        input = StringUtils.replace(input, "%", "\\%");
//        input = StringUtils.replace(input, "_", "\\_");
        return input;
    }

    public static int stringWidth(String s) {
        int len = 0;
        for (char c : s.toCharArray()) {
            len += (CharUtils.isAsciiPrintable(c) ? 1 : 2);
        }
        return len;
    }

    public static String rightPad(String str, int size, char padChar) {
        if (str == null) {
            return null;
        }
        int pads = size - stringWidth(str);
        if (pads <= 0) {
            return str; // returns original String when possible
        }
//        if (pads > PAD_LIMIT) {
//            return rightPad(str, size, String.valueOf(padChar));
//        }
        return str.concat(padding(pads, padChar));
    }

    public static String leftPad(String str, int size, char padChar) {
        if (str == null) {
            return null;
        }
        int pads = size - stringWidth(str);
        if (pads <= 0) {
            return str; // returns original String when possible
        }
//        if (pads > PAD_LIMIT) {
//            return leftPad(str, size, String.valueOf(padChar));
//        }
        return padding(pads, padChar).concat(str);
    }

    //come from StringUtils
    private static final String[] PADDING = new String[Character.MAX_VALUE];

    public static String padding(int repeat, char padChar) {
        // be careful of synchronization in this method
        // we are assuming that get and set from an array index is atomic
        String pad = PADDING[padChar];
        if (pad == null) {
            pad = String.valueOf(padChar);
        }
        while (pad.length() < repeat) {
            pad = pad.concat(pad);
        }
        PADDING[padChar] = pad;
        return pad.substring(0, repeat);
    }
}
